package com.boot.task.controller;

import com.boot.task.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@RestController
public class TaskController {

    @Autowired
    TaskService taskService;

    /**
     * 异步调用
     * @return
     */
    @GetMapping("task")
    public String testTask(){
        long start = System.currentTimeMillis();
        this.taskService.test();
        System.err.println(String.format("任务执行成功,耗时{%s}", System.currentTimeMillis() - start));
        return "success";
    }

    /**
     * 异步调用，同步取结果
     * @return
     */
    @GetMapping("task2")
    public Map<String, Object> testTask2(){
        long start = System.currentTimeMillis();

        Map<String, Object> map = new HashMap<>();
        List<Future<String>> futures = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Future<String> future = taskService.test2(i);
            futures.add(future);
        }
        List<String> response = new ArrayList<>();
        for (Future future : futures) {
            try {
                String string = (String) future.get();
                response.add(string);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        map.put("data", response);
        map.put("消耗时间", String.format("任务执行成功,耗时{%s}毫秒", System.currentTimeMillis() - start));
        return map;
    }
}
